import { TOGGLE_LOGIN, SET_INFO, TOGGLE_SIGN, RESET_DATA } from '@/constants/user'
import Taro from '@tarojs/taro'

let defaultIsLogin = ''
let defaultInfo = ''
let defaultIsSign = ''
try {
  defaultIsLogin = JSON.parse(Taro.getStorageSync('isLogin') || false)
  defaultIsSign = JSON.parse(Taro.getStorageSync('isSign') || false)
  defaultInfo = JSON.parse(Taro.getStorageSync('info') || null)
} catch (e) {
  console.error(e)
}

const INITIAL_STATE = {
  isLogin: defaultIsLogin, // 是否登录
  info: defaultInfo,  // 个人信息(mobile...)
  isSign: defaultIsSign  // 是否认证
}

export default function counter (state = INITIAL_STATE, action) {
  switch (action.type) {
    case TOGGLE_LOGIN:
      Taro.setStorageSync('isLogin', JSON.stringify(action.data))
      return {
        ...state,
        isLogin: action.data
      }
    case TOGGLE_SIGN:
      Taro.setStorageSync('isSign', JSON.stringify(action.data))
      return {
        ...state,
        isSign: action.data
      }
    case SET_INFO:
      let info = {...state.info, ...action.data}
      Taro.setStorageSync('info', JSON.stringify(info))
      return {
        ...state,
        info
      }
    case RESET_DATA:
      Taro.clearStorageSync()
      return {
        isLogin: false,
        isSign: false
      }
    default:
      return state
  }
}
